package com.yicong.ants.ui.scenic;

import android.content.DialogInterface;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.library.baseAdapters.BR;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.adapter.StatefulBindQuickAdapter;
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment;
import com.kennyc.view.MultiStateView;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.scenic.AppointBean;
import com.yicong.ants.bean.scenic.TicketResultBean;
import com.yicong.ants.databinding.AppointHistoryEmptyBinding;
import com.yicong.ants.databinding.RecylerBinding;
import com.yicong.ants.manager.AdapterHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.view.ToCheckTicketsPop;

import java.util.HashMap;
import java.util.Map;

/**
 * 预约历史页面
 *
 * @author cchao
 * @version 2019-07-31.
 */
public class AppointHistoryListFragment extends BaseStatefulFragment<RecylerBinding> {
    StatefulBindQuickAdapter<AppointBean> mAdapter;
    RecyclerView mRecyclerView;

    @Override
    protected int getLayoutId() {
        return R.layout.recyler;
    }

    @Override
    protected void initEventAndData() {
        initRecycler();
        initTopTip(mAdapter);
        onLoadData();
    }

    @Override
    protected void onLoadData() {
        loadPage(mAdapter, 1);
    }

    private void initRecycler() {
        mRecyclerView = mDataBind.recycler;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapter = new StatefulBindQuickAdapter<AppointBean>(R.layout.appoint_item) {
            @Override
            protected void convert(DataBindViewHolder helper, AppointBean item) {
                helper.getBinding().setVariable(BR.bean, item);
//                helper.setTextColor(R.id.appoint_status_text, item.getStatusColor())
                helper.getBinding().setVariable(BR.click, (View.OnClickListener) v -> {
                    switch (v.getId()) {
                        case R.id.action_cancel:
                            UiHelper.showConfirmDialog(mContext, "是否确定取消预约?", (dialog, which) -> {
                                if (which == DialogInterface.BUTTON_POSITIVE) {
                                    cancelAppoint(item);
                                }
                            });
                            break;
                        case R.id.action_get_ticket:
                            getAppointTicket(item);
                            break;
                    }
                });
            }

            @Override
            public void loadPageData(int page) {
                loadPage(mAdapter, page);
            }
        };
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.top = 0;
                outRect.left = UiHelper.dp2px(10);
                outRect.right = UiHelper.dp2px(10);
                outRect.bottom = UiHelper.dp2px(10);
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.bottom = 0;
                }
            }
        });

        mRecyclerView.setAdapter(mAdapter);

        mAdapter.bindToRecyclerView(mRecyclerView);
        // 为空的页面
        if (mAdapter.mStateView instanceof MultiStateView) {
            MultiStateView stateView = ((MultiStateView) mAdapter.mStateView);
            AppointHistoryEmptyBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.appoint_history_empty, stateView, false);
            binding.setClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
            stateView.setViewForState(binding.getRoot(), MultiStateView.VIEW_STATE_EMPTY);
        }
    }

    /**
     * 取消 预约
     */
    private void cancelAppoint(AppointBean item) {
        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("advance_id", item.getAdvance_id());
        map.put("mobile", UserManager.getMobile());
        addSubscribe(RetrofitHelper.getApis().cancelAppoint(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                showToast(respBean.getMsg());
                if (respBean.isCodeFail()) {
                    return;
                }
                onLoadData();
            }, RxHelper.getHideProgressConsumer(this)));
    }

    /**
     * 立即取票
     */
    private void getAppointTicket(AppointBean item) {
        showProgress();
        Map<String, String> params = new HashMap<>(4);
        params.put("advance_id", item.getAdvance_id());
        params.put("mobile", UserManager.getMobile());

        addSubscribe(RetrofitHelper.getApis().getAppointTicket(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showTickets(respBean.getMsg(), null);
                    return;
                }
                showTickets(respBean.getData().getTicket_content(), respBean.getData());
                onLoadData();
            }, RxHelper.getHideProgressConsumer(this)));
    }

    /**
     * 显示我的票务信息
     *
     * @param htmlContent
     * @param isImg
     */
    private ToCheckTicketsPop ticketsPop;

    private void showTickets(String htmlContent, TicketResultBean bean) {
        if (null == ticketsPop) {
            ticketsPop = new ToCheckTicketsPop(mContext);
        }
        ticketsPop.setHtmlContent(htmlContent, bean != null && bean.getTicket_type().equals(Constants.IMG));
        ticketsPop.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 顶部说明
     */
    void initTopTip(StatefulBindQuickAdapter<AppointBean> adapter) {
        View topTip = mLayoutInflater.inflate(R.layout.appoint_history_list_top_tip, null);
        adapter.addHeaderView(topTip);
        adapter.setHeaderAndEmpty(false);
    }

    void loadPage(StatefulBindQuickAdapter adapter, final int page) {
        final Map<String, String> params = new HashMap<>(4);
        params.put("id_card_num", UserManager.getUserBean().getId_card_num());
        params.put("page", String.valueOf(page));

        if (page == 1) {
            mAdapter.setNewData(null);
            adapter.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }
        addSubscribe(RetrofitHelper.getApis().getAppointHistory(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                AdapterHelper.solvePageBean(mDataBind.recycler, page, respBean);
            }, RxHelper.getSwitchableErrorConsumer(adapter)));
    }
}
